﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Hosting;
using Mefisto4.Models;

namespace Mefisto4.Logics
{
    public class M4ModuleLogic
    {
         public static IEnumerable<M4Module> GetAvailableModules()
         {
             var modules = new List<M4Module>();
             foreach (var directory in Directory.GetDirectories(HostingEnvironment.MapPath("~/Modules")))
             {
                 foreach (var file in Directory.GetFiles(directory, "*.dll", SearchOption.TopDirectoryOnly))
                 {
                     var assembly = Assembly.LoadFile(file);
                     if (assembly.GetExportedTypes().Any(t => t.Name.EndsWith("Controller") && t.GetInterfaces().Any(i => i.Name == "IController")))
                         modules.Add(new M4Module
                                         {
                                             Name = assembly.FullName,
                                             NamespaceFullName = assembly.FullName,
                                             RouteModuleName = Path.GetFileName(directory)
                                         });
                 }
             }

             return modules;
         }
    }
}